package com.rn.gypsophila.redis.queue.pubsub;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

import javax.annotation.Resource;

/**
 * Description: Pub/Sub配置
 *
 * @author 然诺
 * @date 2020/05/09
 */
@Configuration
public class PubSubConfig {

	@Resource
	private RedisTemplate redisTemplate;

	@Bean
	public MessageListenerAdapter messageListener() {
		return new MessageListenerAdapter(new RedisMessageSubscriber());
	}

	@Bean
	public RedisMessageListenerContainer redisContainer(RedisConnectionFactory connectionFactory) {
		RedisMessageListenerContainer container = new RedisMessageListenerContainer();
		container.setConnectionFactory(connectionFactory);
		container.addMessageListener(messageListener(), topic());
		return container;
	}

	@Bean
	public MessagePublisher redisPublisher() {
		return new RedisMessagePublisher(redisTemplate, topic());
	}

	@Bean
	public ChannelTopic topic() {
		return new ChannelTopic("messageQueue");
	}

}
